/**
 * 模型拖拽上图功能示意
 */
import axios from "axios"
import { inject, toRaw } from "vue"
import { entityKeys } from "@/common/symbolKeys"
import _ from "lodash"
import {
  getLinesOfOverlayWithFilter,
  drawLine
} from "@/widgets/line-plot/drawLine"

const Cesium = DE.__namespace.Cesium

let leftClickTarget, rightClickTarget, equipPlotLayer, equipPlotLayer2

let viewer // 地图对象

// 初始化当前业务
export function onMounted (mapInstance) {
  viewer = mapInstance // 记录map
  leftClickTarget = inject(entityKeys.LEFT_CLICK_TARGET)()
  rightClickTarget = inject(entityKeys.RIGHT_CLICK_TARGET)()
}

// 释放当前业务
export function onUnmounted () {
  viewer = null
}

// 地图上绘制模型实体
export function deployEquipModel (equipInfo, e, equipPlotLayer) {
  if (!equipInfo || !e) {
    return false
  }
  try {
    const lnglat = cartographic2To3(e, viewer)
    const equip = getEquipByCategory(lnglat, equipInfo)
    const layer = getLayerBaseEffectType(equipInfo.overlayType.toLowerCase())
    if (equip) {
      if (layer) {
        console.log(equip)
        layer.addOverlay(equip)
      } else {
        console.log(equipPlotLayer)
        // window.equipPlotLayer2 && window.equipPlotLayer2.addOverlay(equip)
        equipPlotLayer.addOverlay(equip)
      }
    }
  } catch (e) {
    window.$message(e, "error")
  }
}

const getLayerBaseEffectType = (effectType) => {
  if (!effectType) {
    return
  }
  const vectorType = ["landradar", "conic_sensor_graphics", "attackline", "airborneradar"]
  const primitiveType = ["rectangular_pyramid_sensor_primitive", "custom_sensor_volume_primitive"]
  let layer
  const primitiveLayer = window.$primitiveLayer
  const effectsLayer = window.$effectsLayer
  if (vectorType.includes(effectType)) {
    layer = effectsLayer
  } else if (primitiveType.includes(effectType)) {
    layer = primitiveLayer
  }
  return layer
}

const getEquipByCategory = (lnglat, equipInfo) => {
  let equip
  const categoryType = equipInfo.category + ""

  if (categoryType === "1010") {
    equip = new DE.Billboard(lnglat, equipInfo.icon2d)
    equip.attr = { ...equipInfo }
    const equipStyle = {
      // 宽度（以像素为单位）
      width: 50, // 高度（以像素为单位）
      height: 50, // 逆时针旋转
      // 大小是否以米为单位
      // sizeInMeters: false,
      // 相对于坐标的水平位置
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的垂直位置
      verticalOrigin: Cesium.VerticalOrigin.CENTER, // 设置颜色和透明度
      // color: self.Cesium.Color.WHITE.withAlpha(0.8),
      // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
      // pixelOffset: new Cesium.Cartesian2(10, 0),
      // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
      scale: 1.5,
      opacity: 1.0
    }
    equip.name = equipInfo.name
    equip.setStyle(equipStyle)
    equip.setLabel(equipInfo.name, {
      showBackground: false,
      font: "16px monospace",
      outlineColor: Cesium.Color.fromCssColorString("white").withAlpha(0.5),
      style: Cesium.LabelStyle.FILL_AND_OUTLINE, // FILL_AND_OUTLINE
      outlineWidth: 3,
      fillColor: Cesium.Color.RED,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(15, -15)
    })
  } else if (categoryType === "2010") {
    const _pos = _.cloneDeep(lnglat)
    switch (equipInfo.overlayType.toLowerCase()) {
      case "landradar":
        equip = new DE.DynamicLandRadar(_pos)
        break
      case "airborneradar":
        _pos[2] = 100000
        equip = new DE.DynamicAirborneRadar(_pos)
        break
      case "conic_sensor_graphics":
        _pos[2] = 1000000
        equip = new DE.ConicSensorGraphics(_pos)
        break
      case "rectangular_pyramid_sensor_primitive":
        _pos[2] = 1000000
        equip = new DE.RectangularPyramidSensorPrimitive(_pos)
        equip.setStyle({
          radius: 5000000
        })
        break
      case "custom_sensor_volume_primitive":
        _pos[2] = 1000000
        equip = new DE.CustomSensorVolumePrimitive(_pos)
        equip.setStyle({
          radius: 5000000
        })
        break
      case "attackline":
        equip = new DE.DynamicAttackLine(_pos)
        break
    }
  }
  return equip
}

// 屏幕坐标转经纬度
const cartographic2To3 = (event, viewer) => {
  const x = parseFloat(event.x)
  const y = parseFloat(event.y)
  const earthPosition = viewer.camera.pickEllipsoid(
    {
      x,
      y
    },
    viewer.scene.globe.ellipsoid
  )
  const point = Cesium.Cartographic.fromCartesian(earthPosition, viewer.scene.globe.ellipsoid, new Cesium.Cartographic())
  return [Cesium.Math.toDegrees(point.longitude), Cesium.Math.toDegrees(point.latitude), 0]
}

// 获取装备树状结构伪数据
export function getModelCategoryTree () {
  return axios({ url: "testData/equip/equipCategoryTree.json" })
}

// 根据装备类型获取伪数据
export async function getModelList (category, type) {
  const res = await axios({ url: "testData/equip/equipList.json" })
  return new Promise((resolve, reject) => {
    const d = res.data.data.filter((item) => {
      return item.category === category && item.type === type
    })
    resolve(d)
  })
}

export function drawAirLine (pickInfo) {
  const { overlay } = pickInfo
  drawLine({
    overlay,
    type: "airline",
    layer: window?.$actionPlotLayer,
    style: { color: "red" },
    attr: {
      type: "airline",
      equipId: overlay.overlayId
    },
    rules: {
      couldCreateLine: (overlay) => {
        return (
          overlay &&
          overlay instanceof DE.Overlay &&
          !getLinesOfOverlayWithFilter(overlay, (overlay, line) => {
            return line && line?.attr?.equipIds?.includes(overlay.overlayId) && line.attr?.type === "airline"
          }).length &&
          overlay.position
        )
      }
    },
    callback: (line) => {
      console.log(line)
    }
  })
}
